import { createRouter, createWebHistory, RouteRecordRaw, createWebHashHistory } from "vue-router";
import store from "../store/index";
import permissionList from "@/utils/router-permission";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { DynamicRoutesList } from "./DynamicRoutes";
import { getToken, getCookies } from "@/utils/auth";
import { Session } from "@/utils/storage";
import { DynamicRoutesListTwo } from "./DynamicRoutes2";
import { filterAsyncRouters, loadView } from "@/store/actions";
import { userHook } from "@/hooks/userHook/userHook";
import hook from "@/hooks";
import { replace } from "lodash-es";
import { buildMenuTree, getMenuTree } from "./menuHelper";
const basePath: any = import.meta.env.VITE_DEV_PREFIX;
// "/bigScreen",
// "/personalInfo",
// "/itf/organization/*",
// "/itf/employee/*",
const whiteList = [
  "/login",
  "/register",
  "/404",
  "/401",
];

const CommonRoutes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "login",
    component: () => import("@/pages/login/login.vue"),
    meta: {
      name: "登录",
    },
  },
  {
    path: "/:pathMatch(.*)*",
    // name: '404',
    meta: {
      name: '404'
    },
    component: () => import("@/pages/error/404/index.vue"),
  },
  {
    path: "/401",
    // name: '401',
    component: () => import("@/pages/error/401/index.vue"),
    meta: {
      name: "401",
    },
  },
];

export const DynamicRoutes: any = new DynamicRoutesList().list();
export const DynamicRoutesTwo: any = new DynamicRoutesListTwo().list();
const routes: Array<RouteRecordRaw> = [...DynamicRoutes, ...CommonRoutes];

// console.log('basePath======>', basePath);

// const routes: Array<RouteRecordRaw> = [...DynamicRoutesTwo, ...CommonRoutes];
const router = createRouter({
  history: createWebHistory(basePath),
  // history: createWebHashHistory(basePath),
  routes,
});
router.beforeEach((to: any, from: any, next: any) => {
  NProgress.start();
  sessionStorage.setItem("currentPath", to.name);
  store.state.currentPath = to.name
  const matchedd = to.matched && to?.matched && to?.matched;
  matchedd?.length > 1 && (hook.menuHook.menuFirstChoose = matchedd[1].name);
  if (getCookies(getToken()) && hook.menuHook.menuList && hook.menuHook.menuList?.length) {
    // const hasRoles = userHook.roleList && userHook.roleList?.length > 0;
    // if (hasRoles) {
    if (to.name) {
      // || to.path === ''  || to.path === basePath
      if (from.name != 'undefined' && to.path === '' || to.path === '/' || to.path === basePath) {
        console.log('进入登录页面');
        next({ path: `/login` });
        NProgress.done();
      }
      else {
        // store.dispatch("GenerateRoutes", getMenuTree() ?? []).then(() => {
        //   next({ ...to, replace: true });
        //   NProgress.done();
        // })
        next();
        NProgress.done();
      }
    }
    else {
      store.dispatch("GenerateRoutes", getMenuTree() ?? []).then(() => {
        next({ ...to, replace: true });
        NProgress.done();
      })
    }
    // }
    // else {
    //   next();
    //   NProgress.done()
    // }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next();
      NProgress.done();
    } else {
      // ${basePath}
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
      NProgress.done();
    }
  }
});

// 这里简化路由对象 只取需要的字段
type CrumbObj = {
  name: string;
  meta: {
    name: string;
    hide: Boolean;
  };
};

router.afterEach((to: any, from: any, _next: any) => {
  const arr = to.meta.hide ? [from, to] : to.matched;
  // console.log('arrarrarrarr=>', [from, to], 'to.matched:', to.matched);
  let routerList = [] as Array<CrumbObj>;
  arr.forEach((item: any) => {
    const obj: CrumbObj = {
      name: item.name,
      meta: {
        name: item.meta.name,
        hide: item.meta.hide,
      },
    };
    routerList.push(obj);
  });
  if (to.meta.hide) {
    //顶部面包屑
    store.commit("SET_CRUMB_LIST", routerList);
    //目前左边导航选中的active
    store.commit("SET_CURRENT_MENU", to.name);
  } else {
    routerList = routerList.splice(1);
    //顶部面包屑
    store.commit("SET_CRUMB_LIST", routerList);
    if (!to.meta.isSub) {
      //目前左边导航选中的active
      store.commit("SET_CURRENT_MENU", to.name);
    }
  }
  NProgress.done();
});
// // 防止连续点击多次路由报错
// let routerPush = router.push;
// let routerReplace = router.replace;
// // push
// router.push = function push(location) {
//   return routerPush.call(this, location).catch(err => err)
// }
// // replace
// router.replace = function push(location) {
//   return routerReplace.call(this, location).catch(err => err)
// }




export default router;
